<template>
  <div class="manage-schools">
    <div class="page-header">
      <h1>学校管理</h1>
      <el-button type="primary" @click="showAddDialog = true">添加新学校</el-button>
    </div>

    <!-- 搜索和过滤 -->
    <div class="search-bar">
      <el-input
        v-model="searchQuery"
        placeholder="搜索学校名称"
        prefix-icon="el-icon-search"
        clearable
        @clear="loadSchools"
      ></el-input>
      <el-button type="primary" @click="searchSchools">搜索</el-button>
    </div>

    <!-- 学校列表 -->
    <el-table
      :data="displayedSchools"
      style="width: 100%"
      border
      stripe
      :header-cell-style="{ backgroundColor: '#1f1b24', color: '#ffffff' }"
      :cell-style="{ backgroundColor: '#28232e', color: '#b0bec5' }"
      v-loading="loading"
    >
      <el-table-column prop="id" label="ID" width="100"></el-table-column>
      <el-table-column prop="name" label="学校名称" width="200"></el-table-column>
      <el-table-column label="学校图标" width="120">
        <template #default="scope">
          <img
            :src="scope.row.logo || '../../components/icons/touxiang.png'"
            alt="学校图标"
            style="width: 50px; height: 50px; border-radius: 50%;"
          >
        </template>
      </el-table-column>
      <el-table-column prop="address" label="地址"></el-table-column>
      <el-table-column prop="clubCount" label="社团数量" width="100"></el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            @click="editSchool(scope.row)"
          >编辑</el-button>
          <el-button
            size="small"
            type="danger"
            @click="confirmDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next"
        :total="totalItems"
        background
      ></el-pagination>
    </div>

    <!-- 添加学校对话框 -->
    <el-dialog
      title="添加新学校"
      v-model="showAddDialog"
      width="50%"
      :close-on-click-modal="false"
    >
      <el-form :model="schoolForm" :rules="schoolRules" ref="schoolFormRef" label-width="100px">
        <el-form-item label="学校名称" prop="name">
          <el-input v-model="schoolForm.name"></el-input>
        </el-form-item>
        <el-form-item label="学校图标">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :auto-upload="false"
            :http-request="handleManualUpload"
          >
            <img v-if="schoolForm.logo" :src="schoolForm.logo" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="schoolForm.address"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="submitSchool">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑学校对话框 -->
    <el-dialog
      title="编辑学校"
      v-model="showEditDialog"
      width="50%"
      :close-on-click-modal="false"
    >
      <el-form :model="schoolForm" :rules="schoolRules" ref="schoolFormRef" label-width="100px">
        <el-form-item label="学校名称" prop="name">
          <el-input v-model="schoolForm.name"></el-input>
        </el-form-item>
        <el-form-item label="学校图标">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :auto-upload="false"
            :http-request="handleManualUpload"
          >
            <img v-if="schoolForm.logo" :src="schoolForm.logo" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="schoolForm.address"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditDialog = false">取消</el-button>
          <el-button type="primary" @click="updateSchool">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
      title="确认删除"
      v-model="showDeleteDialog"
      width="30%"
    >
      <p>确定要删除学校 "{{ schoolToDelete?.name }}" 吗？此操作不可撤销。</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDeleteDialog = false">取消</el-button>
          <el-button type="danger" @click="deleteSchool">删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import axios from 'axios';
import { ElMessage, ElLoading } from 'element-plus';

// 状态变量
const allSchools = ref([]); // 存储所有的学校数据
const loading = ref(false);
const searchQuery = ref('');
const currentPage = ref(1);
const pageSize = ref(20);
const totalItems = ref(0);
const showAddDialog = ref(false);
const showEditDialog = ref(false);
const showDeleteDialog = ref(false);
const schoolToDelete = ref(null);
const schoolFormRef = ref(null);

// 学校表单
const schoolForm = ref({
  id: '',
  name: '',
  logo: '',
  address: '',
  clubCount: 0,
  logoFile: null
});

// 表单验证规则
const schoolRules = {
  name: [
    { required: true, message: '请输入学校名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入学校地址', trigger: 'blur' }
  ]
};

// 计算当前页应该显示的数据
const displayedSchools = computed(() => {
  let result = allSchools.value;

  // 如果有搜索条件，先过滤
  if (searchQuery.value.trim()) {
    result = result.filter(school =>
      school.name.toLowerCase().includes(searchQuery.value.toLowerCase())
    );
  }

  // 记录总数，用于分页组件
  totalItems.value = result.length;

  // 执行分页
  const startIndex = (currentPage.value - 1) * pageSize.value;
  const endIndex = Math.min(startIndex + pageSize.value, result.length);
  return result.slice(startIndex, endIndex);
});

// 加载学校数据
const loadSchools = async () => {
  loading.value = true;
  try {
    const response = await axios.get('http://localhost:5000/school');

    // 处理所有学校数据
    allSchools.value = response.data.map(school => ({
      ...school,
      clubCount: school.clubs ? school.clubs.length : 0,
      logo: school.logo ? `http://localhost:5000/uploads/${school.logo}` : 'src/components/icons/touxiang.png'
    }));

    loading.value = false;
  } catch (error) {
    console.error('获取学校列表失败:', error);
    ElMessage.error('获取学校列表失败');
    loading.value = false;
  }
};

// 搜索学校
const searchSchools = () => {
  currentPage.value = 1; // 重置为第一页
};

// 分页变化
const handleCurrentChange = (page) => {
  currentPage.value = page;
};

// 编辑学校
const editSchool = (school) => {
  schoolForm.value = {
    ...school,
    logoFile: null // 重置文件对象
  };
  showEditDialog.value = true;
};

// 确认删除
const confirmDelete = (school) => {
  schoolToDelete.value = school;
  showDeleteDialog.value = true;
};

// 删除学校
const deleteSchool = async () => {
  try {
    await axios.delete(`http://localhost:5000/school/${schoolToDelete.value.id}`);

    // 从列表中移除
    allSchools.value = allSchools.value.filter(school => school.id !== schoolToDelete.value.id);
    ElMessage.success('删除成功');
    showDeleteDialog.value = false;
    schoolToDelete.value = null;
  } catch (error) {
    console.error('删除学校失败:', error);
    ElMessage.error('删除学校失败');
  }
};

// 提交新学校
const submitSchool = async () => {
  if (!schoolFormRef.value) return;

  await schoolFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 准备FormData对象用于文件上传
        const formData = new FormData();
        formData.append('name', schoolForm.value.name);
        formData.append('address', schoolForm.value.address);

        // 如果有logo文件，添加到formData
        if (schoolForm.value.logoFile) {
          formData.append('logo', schoolForm.value.logoFile);
        }

        const response = await axios.post('http://localhost:5000/school', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });

        // 添加到学校列表
        const newSchool = {
          ...response.data,
          clubCount: 0,
          logo: response.data.logo ? `http://localhost:5000/uploads/${response.data.logo}` : 'src/components/icons/touxiang.png'
        };

        allSchools.value.push(newSchool);
        ElMessage.success('添加成功');
        showAddDialog.value = false;
        schoolForm.value = { name: '', logo: '', address: '', clubCount: 0, logoFile: null };
      } catch (error) {
        console.error('添加学校失败:', error);
        ElMessage.error('添加学校失败');
      }
    }
  });
};

// 更新学校
const updateSchool = async () => {
  if (!schoolFormRef.value) return;

  await schoolFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 准备FormData对象用于文件上传
        const formData = new FormData();
        formData.append('name', schoolForm.value.name);
        formData.append('address', schoolForm.value.address);

        // 如果有logo文件，添加到formData
        if (schoolForm.value.logoFile) {
          formData.append('logo', schoolForm.value.logoFile);
        }

        const response = await axios.put(`http://localhost:5000/school/${schoolForm.value.id}`, formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });

        // 更新学校列表中的数据
        const index = allSchools.value.findIndex(school => school.id === schoolForm.value.id);
        if (index !== -1) {
          const updatedSchool = {
            ...response.data,
            clubCount: response.data.clubs ? response.data.clubs.length : 0,
            logo: response.data.logo ? `http://localhost:5000/uploads/${response.data.logo}` : 'src/components/icons/touxiang.png'
          };
          allSchools.value[index] = updatedSchool;
        }

        ElMessage.success('更新成功');
        showEditDialog.value = false;
      } catch (error) {
        console.error('更新学校失败:', error);
        ElMessage.error('更新学校失败');
      }
    }
  });
};

// 处理头像上传
const handleAvatarSuccess = (res, file) => {
  // 存储本地预览URL
  schoolForm.value.logo = URL.createObjectURL(file.raw);
  // 存储文件对象供后续提交使用
  schoolForm.value.logoFile = file.raw;
};

// 上传前校验
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!');
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!');
  }
  return isJPG && isLt2M;
};

// 处理手动上传（阻止自动上传）
const handleManualUpload = ({ file }) => {
  handleAvatarSuccess(null, { raw: file });
};

// 组件加载时获取学校列表
onMounted(() => {
  loadSchools();
});
</script>

<style scoped>
.manage-schools {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  color: #ffffff;
}

.search-bar {
  display: flex;
  margin-bottom: 20px;
  gap: 10px;
}

.search-bar .el-input {
  width: 300px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100px;
  height: 100px;
  display: inline-block;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}
</style>